﻿using Brc_PaaS.Common.Helper;
using Brc_PaaS.Common.Model.Basic;
using Brc_PaaS.Common.Model.RabbitMq;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Text;

namespace Brc_PaaS.Core.RabbitMq
{
    public class RabbitMqClient : IRabbitMqClient
    {

        public BaseResponseModel SendMessage(RabbitMQSettingEntity entity, EventMessage eventMessage, string queueName)
        {
            BaseResponseModel result = new BaseResponseModel() { IsSuccess = false, Msg = string.Empty };
            var _connectionPool = new RabbitMQConnectionPool(entity);
            string type;
            switch (entity.ExchangeType)
            {
                case ExChangeType.Fanout:
                    type = ExchangeType.Fanout;
                    break;
                case ExChangeType.Direct:
                    type = ExchangeType.Direct;
                    break;
                case ExChangeType.Topic:
                default:
                    type = ExchangeType.Topic;
                    break;
            }
            result = SendMessage(entity.ExchangeName, type, eventMessage, _connectionPool, queueName, entity.RouteKey);
            return result;
        }

        private BaseResponseModel SendMessage(string exchangeName, string type, EventMessage eventMessage, RabbitMQConnectionPool connectionPool, string queueName, string routeKey)
        {
            BaseResponseModel result = new BaseResponseModel() { IsSuccess = false, Msg = string.Empty };
            var connection = connectionPool.CreateMQConnectionInPoolNew();
            try
            {
                using (var channel = connection.CreateModel())
                {
                    //定义交换机
                    channel.ExchangeDeclare(exchangeName, type, true, false);
                    //定义队列
                    channel.QueueDeclare(queueName, true, false, false);
                    //将队列绑定到交换机
                    channel.QueueBind(queueName, exchangeName, routeKey);
                    //将消息转换成字节数组
                    var messageJson = JsonHelper.SerializeObject(eventMessage);
                    var sendBytes = Encoding.UTF8.GetBytes(messageJson);
                    //发送消息
                    channel.BasicPublish(exchangeName, routeKey, null, sendBytes);
                }
                result.IsSuccess = true;
                return result;
            }
            catch (Exception ex)
            {
                result.Msg = ex.Message;
                return result;
            }
            finally
            {
                connectionPool.ResetMQConnectionToFree(connection);
            }
        }


    }
}
